<template>
  <div>
    <van-nav-bar
      title="修改昵称"
      left-text="取消"
      right-text="保存"
      @click-left="$emit('closeEdit')"
      @click-right="onClickRight"
    />
    <van-field
      v-model="nickName"
      rows="2"
      autosize
      type="textarea"
      border
      maxlength="10"
      placeholder="请输入昵称"
      show-word-limit
    />
  </div>
</template>

<script>
import { updataUserData } from '@/api/user'
export default {
  name: 'edit-name',
  props: {
    value: {
      required: true,
      type: String
    }
  },
  data () {
    return {
      nickName: ''
    }
  },

  created () {
    this.nickName = this.value
  },

  methods: {
    async onClickRight () {
      if (this.nickName === this.value) {
        return this.$toast('昵称不能与原昵称相同')
      }
      this.$toast.loading({
        message: '修改中...',
        forbidClick: true
      })
      try {
        await updataUserData({ name: this.nickName })
        this.$emit('closeEdit')
        this.$emit('input', this.nickName)
        this.$toast.success('更新昵称成功')
      } catch (err) {
        if (err.response && err.response.status === 409) {
          this.$toast('用户名被占用')
        }
        this.$toast('更改失败')
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
